package client

import (
	"context"
	"gitee.com/enjoy_5/integral-rpc/consts"
	"gitee.com/enjoy_5/integral-rpc/proto/integral"
	"gitee.com/xuxinzhi2206/corehub/nacos"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"time"
)

func client(ctx context.Context, hand func(c integral.IntegralClient) error) error {
	service, err := nacos.FindHealthService(consts.ServiceName, consts.GroupName)
	if err != nil {
		return err
	}
	conn, err := grpc.NewClient(service, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		return err
	}

	defer conn.Close()
	c := integral.NewIntegralClient(conn)

	// Contact the server and print out its response.
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	return hand(c)
}

// 获取积分详情
func GetIntegralInfo(ctx context.Context, userId int64) (infos *integral.IntegralInfo, err error) {
	err = client(ctx, func(c integral.IntegralClient) error {
		integralInfos, err := c.GetIntegralInfo(ctx, &integral.GetIntegralInfoRequest{UserId: userId})
		if err != nil {
			return err
		}

		infos = integralInfos.GetInfo()

		return err
	})
	return
}

// 创建积分记录表
func CreateIntegralRecord(ctx context.Context, in *integral.IntegralRecordInfo) (infos *integral.IntegralRecordInfo, err error) {
	err = client(ctx, func(c integral.IntegralClient) error {
		integralRecordInfo, err := c.CreateIntegralRecordInfo(ctx, &integral.CreateIntegralRecordInfoRequest{In: in})
		if err != nil {
			return err
		}

		infos = integralRecordInfo.GetInfo()

		return err
	})
	return
}

// 积分记录列表
func GetIntegralRecordList(ctx context.Context, userId int64) (infos []*integral.IntegralRecordInfo, err error) {
	err = client(ctx, func(c integral.IntegralClient) error {
		list, err := c.GetIntegralRecordInfoList(ctx, &integral.GetIntegralRecordInfoListRequest{UserId: userId})
		if err != nil {
			return err
		}

		infos = list.GetInfo()

		return err
	})
	return
}
